<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Horarios extends CI_Controller
{
	private $table = "horarios";
	private $pk = "id";
	
	function __construct()
	{
		parent::__construct();
		if (!$this->session->userdata('loggedin'))
		{
			redirect(base_url(), 'refresh');
		}
	}
	
	function index()
	{
		$objSearch = null;
		
		$objSearch->groupOp = "AND";
		$objSearch->rules[0]->field = "flag_deletado";
		$objSearch->rules[0]->op = "eq";
		$objSearch->rules[0]->data = "N";
	    
		$data['medicos'] = $this->generic_model->getByFilter($objSearch, "medicos");
		$data['dias_semana'] = $this->generic_model->getByFilter($objSearch,"dias_semana");
	    
		$this->load->view('common/header');
		$this->load->view('common/menu');
		$this->load->view('horarios', $data);
		$this->load->view('common/footer');
	}
	
	function listAll()
	{
	    parse_str($_SERVER['QUERY_STRING'],$_GET);
	    $objSearch = null;
		
		$objSearch->groupOp = "AND";
		$objSearch->rules[0]->field = "tb_horarios.flag_deletado";
		$objSearch->rules[0]->op = "eq";
		$objSearch->rules[0]->data = "N";
		
		if(isset($_REQUEST['filters']) && !is_null($_REQUEST['filters']) && !empty($_REQUEST['filters']))
		{
			$objSearch = json_decode(stripslashes($_REQUEST['filters']));
		}

		$data['page'] = isset($_GET['page'])?$_GET['page']:1;
		$data['rows'] = isset($_GET['rows'])?$_GET['rows']:10;
		$data['sidx'] = isset($_GET['sidx'])?$_GET['sidx']:'id';
		$data['sord'] = isset($_GET['sord'])?$_GET['sord']:'';
		
		$this->load->model('horarios_model');
		$dados['horarios'] = $this->horarios_model->getByFilterPaging($objSearch, $this->table, $data);
		$i = 0;
		$responce = null;
		$responce->page = $dados['horarios']['page'];
		$responce->total = $dados['horarios']['totalpages'];
		$responce->records = $dados['horarios']['totalrecords'];

		foreach ($dados['horarios']['result'] as $row)
		{
			$responce->rows[$i]['id']=$row->id;
        	$responce->rows[$i]['cell']=array($row->id, $row->nome, $row->dia, $row->horario, $row->flag_disponivel_site);
        	$i++;
		}
		echo json_encode($responce);
	}
	
	function save()
	{
		$config = array(
			array(
				'field' => "id_medicos_fk",
				'label' => "M&eacute;dico",
				'rules' => "trim|required|min_length[1]|integer|xss_clean"
			),
			array(
				'field' => "id_dias_semana_fk",
				'label' => "Dias",
				'rules' => "trim|required|xss_clean"
			),
			array(
				'field' => "horario",
				'label' => "Hor&aacute;rio",
				'rules' => "trim|required|min_length[5]|max_length[8]|xss_clean"
			),
			array(
				'field' => "flag_disponivel_site",
				'label' => "Dispon&iacute;vel no Site?",
				'rules' => "trim|required|min_length[1]|max_length[1]|xss_clean"
			)
		);
		
		$this->form_validation->set_rules($config);
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->index();
			echo "err#".$this->form_validation->error_string;
			exit;
		}
		else
		{	
			$action = $this->input->post('hid_oper');
			$data['id_medicos_fk'] = $this->input->post('id_medicos_fk');
			$data['horario'] = $this->input->post('horario');
			$data['flag_disponivel_site'] = $this->input->post('flag_disponivel_site');
			switch ($action)
			{
				case "add":
				    $flag_erro = true;
                    $dias = explode("##",$this->input->post('id_dias_semana_fk'));
                    for ($i = 0; $i < count($dias)-1; $i++) 
                    {
                        $data['id_dias_semana_fk'] = $dias[$i];
    					if ($this->generic_model->insert($data, $this->table))
    					{
    					    $flag_erro = false;
    					}
    					else 
    					{
    					    $flag_erro = true;
    					}
                    }				    
					
					if ($flag_erro)
					{
						echo "err#Erro na inser&ccedil;&atilde;o do Hor&aacute;rio";
					}
					else
					{
						$this->index();
						echo "oks#Hor&aacute;rio inserido com sucesso!";
					}
					break;
				case "upd":
					$data['id'] = $this->input->post('id', TRUE);
					if($this->generic_model->update($data,$this->table, $this->pk))
					{
						$this->index();
						echo "oks#Hor&aacute;rio atualizado com sucesso!";
					}
					else 
					{
						echo "err#Erro na atualiza&ccedil;&atilde;o do Hor&aacute;rio";
					}
					break;
			}
			exit;
		}
	}
	
	function getById()
	{
		$data['id'] = $this->input->post('id');
		$dados['horario'] = $this->generic_model->getById($data, $this->table, $this->pk);
		$i = 0;
		$responce = null;
		foreach ($dados['horario'] as $row)
		{
			$responce->rows[$i]['id']=$row->id;
        	$responce->rows[$i]['cell']=array($row->id, $row->id_medicos_fk, $row->id_dias_semana_fk, $row->horario, $row->flag_disponivel_site);
        	$i++;
		}
		echo json_encode($responce);
	}
	
	function delete()
	{
		$data['id'] = $this->input->post('id');
		$data['flag_deletado'] = "S";
		if($this->generic_model->update($data, $this->table, $this->pk))
		{
			$this->index();
			echo "oks#Hor&aacute;rio exclu&iacute;do com sucesso!";
		}
		else
		{
			echo "err#Erro na exclus&atilde;o do Hor&aacute;rio";
		}
		exit;
	}	

    function getDias()
    {
		$objSearch = null;
		
		$objSearch->groupOp = "AND";
		$objSearch->rules[0]->field = "tb_medicos_dias_semana.flag_deletado";
		$objSearch->rules[0]->op = "eq";
		$objSearch->rules[0]->data = "N";
        
		$objSearch->rules[1]->field = "tb_medicos_dias_semana.id_medicos_fk";
		$objSearch->rules[1]->op = "eq";
		$objSearch->rules[1]->data = $this->input->post('id_medicos_fk');
		$this->load->model('horarios_model');
		$dias = $this->horarios_model->getDiasMedico($objSearch);
		
		$msg  = "";
		$msg .= "<table border='0' cellpadding='0' cellspacing='0'>";
		$msg .= "	<tr>";
		$msg .= "		<td colspan='4'>";
		$msg .= "			<label for='id_dias_semana_fk'>Dias de Atendimento</label><br />";
		$msg .= "		</td>";
		$msg .= "	</tr>";
			for ($i=0; $i<count($dias); $i)
			{
		$msg .= "	<tr>";
			    for($x=0; $x<4; $x++)
				{
					if($i < count($dias))
					{
		$msg .= "		<td>";
		$msg .= "			<input type='checkbox' name='id_dias_semana_fk' id='id_dias_semana_fk' class='dias_semana' value='".$dias[$i]->id."' />". htmlentities(utf8_decode($dias[$i]->descricao));
		$msg .= "		</td>";
					}
					$i++;
				}
		$msg .= "	</tr>";
			}
		$msg .= "</table>";
		
		echo $msg;
    }
}